ti.datatable=function(url,name,maxRow){
	ti.datatables[name] = this;
	this.url = url;
	this.name = name;
	this.cols = [];
	this.sortCol;
	this.sortDir;
	this.maxRow = maxRow;
	this.pageSelect = ti(name+'_page_select');
	this.curPage = this.pageSelect.options.selectedIndex;
	var counter=0;
	var obj = ti(name+'_col_'+counter);
	while(obj){
		var classes=ti.getClasses(obj);
		if(classes['datatable_column_sortdesc']){
			this.sortCol = counter;
			this.sortDir = 'desc';
		}
		if(classes['datatable_column_sortasc']){
			this.sortCol = counter;
			this.sortDir = 'asc';
		}
		this.cols.push(obj);
		counter++;
		obj = ti(name+'_col_'+counter);
	}
	var curMax = 0;
	var obj = ti(name+'_'+curMax);
	while(obj){
		if(curMax < this.maxRow){
			obj.style.display='';
		}else{
			obj.style.display='none';
		}
		curMax++;
		obj = ti(name+'_'+curMax);
	}
}
ti.datatables={};

ti.datatable.prototype.page=function(dir,newPage){
	switch(dir){
		case 'first':
			if(this.curPage > 0)
				this.curPage=0;
			else{
				alert('You are already on the first page');
				return;
			}
			break;
		case 'previous':
			if(this.curPage > 0)
				this.curPage--;
			else{
				alert('You are already on the first page');
				return;
			}
			break;
		case 'next':
			if(this.curPage < (this.pageSelect.options.length - 1))
				this.curPage++;
			else{
				alert('You are already on the last page');
				return;
			}
			break;
		case 'last':
			if(this.curPage < (this.pageSelect.options.length - 1))
				this.curPage = (this.pageSelect.options.length - 1);
			else{
				alert('You are already on the last page');
				return;
			}
			break;
		case 'set':
			this.curPage = newPage;
			break;
	}
	this.pageSelect.options.selectedIndex = this.curPage;
	this.getData();
}

ti.datatable.prototype.sort=function(newCol){
	var obj = ti(this.name+'_col_'+this.sortCol);
	var classes = ti.getClasses(obj);
	if(this.sortCol == newCol){
		classes['datatable_column_sort'+this.sortDir] = false;
		this.sortDir = (this.sortDir == 'desc')?'asc':'desc';
	}else{
		classes['datatable_column_sort'+this.sortDir] = false;
		ti.setClasses(obj,classes);
		this.sortCol=newCol;
		this.sortDir='asc';
		var obj = ti(this.name+'_col_'+this.sortCol);
		classes = ti.getClasses(obj);
	}
	classes['datatable_column_sort'+this.sortDir] = true;
	ti.setClasses(obj,classes);
	this.curPage = 0;
	this.pageSelect.options.selectedIndex = this.curPage;
	this.getData();
}

ti.datatable.prototype.getData=function(){	
	var data = '&block='+this.name;
	data += '&'+this.name+'_page='+this.curPage;
	data += '&'+this.name+'_sort_col='+this.sortCol;
	data += '&'+this.name+'_sort_dir='+this.sortDir;
	//alert(data);
	ti.ajax(this.url,data);
}
